
function userCtrl($scope,$modal){
    $scope.queryUserList = function(){
        userQuery($scope,'');
    }

    $scope.openBox_update = function (user) {
        $scope.user_update=user;
        var $modalInstance = $modal.open({
            templateUrl: 'views/admin_user_update_page.html',
            controller: User_ModalCtrl,
            scope:$scope
        });
    };

    $scope.openBox_insert = function () {
        var $modalInstance = $modal.open({
            templateUrl: 'views/admin_user_insert_page.html',
            controller: User_ModalCtrl,
            scope:$scope
        });
    };

    $scope.deleteUsers = function(){
        var ck_user_Id = $("input:checkbox[name=ck_user_Id]:checked");
        if(ck_user_Id.length==0){
            alert('至少删除一个用户');
            return;
        }
        var arr = [];
        for(var i=0;i<ck_user_Id.length;i++){
            arr.push(ck_user_Id[i].value);
        }
        userDelete($scope,arr);
    }
    $scope.openBox_authoriztion = function(){
        $scope.changedNodes = [];
        var ck_user_Id = $("input:checkbox[name=ck_user_Id]:checked");
        if(ck_user_Id.length==0||ck_user_Id.length>1){
            alert('一次最多对一个用户进行权限管理');
            return;
        }
        $scope.currUserId = ck_user_Id[0].value;
        $scope.userSchemaList=null;
        $scope.zNodes=null;
        readUserSchemaList($scope);
        readZNodes($scope);



        var _c = setInterval(function(){
            if($scope.userSchemaList==null||$scope.zNodes==null){
                return;
            }
            currNode=undefined;
            var $modalInstance = $modal.open({
                templateUrl: 'views/admin_authorization_update_page.html',
                controller: User_ModalCtrl,
                scope:$scope
            });
            clearInterval(_c);
        },100);
    }

    $scope.setting = {
        edit : {
            enable : true,
            showRemoveBtn : false,
            showRenameBtn : false
        },
        check : {
            enable : true,//设置 zTree 的节点上是否显示 checkbox / radio 默认false
            chkStyle : "checkbox",//勾选框类型(checkbox 或 radio)
            chkboxType : {
                "Y" : "ps",
                "N" : "ps"
            },//勾选 checkbox 对于父子节点的关联关系 Y 属性定义 checkbox 被勾选后的情况,"p" 表示操作会影响父级节点
            chkDisabledInherit : false,//是否继承父类的chkDisabled:true属性(不可操作)
            nocheckInherit : false//是否集成父类的nocheck:true属性(不显示复选框)
        },
        data : {
            simpleData : {
                enable : true,
                idKey : "id",
                pIdKey : "pId",
                rootPId : 0
            }
        },
        callback : {
            beforeClick : zTreeBeforeClick,
            onCheck : onCheck
        }
    };

}
var currNode;
function zTreeBeforeClick(treeId, treeNode, clickFlag){
    currNode = treeNode;
}
var schemaIdList;
function onCheck(e,treeId,treeNode){
    //循环遍历找到根节点
    var root = treeNode;
    var schemaIds = [];
    while(root.getParentNode()!=null){
        root = root.getParentNode();
    }
    $.each(root.children,function(i,v){
        if(!v.children){return}
        $.each(v.children,function(j,m){

            var authorization = 0;
            $.each(m.children,function(k,n){
                if(n.checked){
                    authorization+=Number(n.t);
                }
            });
            authorization+="";
            var len = authorization.length;
            for(var _i=0;_i<4-len;_i++){
                authorization = "0"+authorization;
            }
            if(m.checked){
                schemaIds.push(m.t+":"+authorization);
            }
        });
    });
    schemaIdList = schemaIds.join(",");
}

//获取Tree节点
function readZNodes($scope){
    var _c = setInterval(function(){
        if($scope.userSchemaList==null){
            return;
        }

        var arr = new Array();
        var root = {'id':1,'pid':0,'name':'root',open:true};
        arr.push(root);
        var count = 2;
        $.ajax({
            url: '/db/doReadDbListWithSchema',
            success: function (data) {
                var responseObj = $.parseJSON(data);
                if (responseObj.success) {
                    $scope.$apply(function () {
                        $.each(responseObj.dataList, function(i, v) {
                            var pId = count++;

                            var dbRemark='';
                            $.each($scope.dbRemarkList,function(o,v1){
                                if(v1.dbId== v.id){
                                    dbRemark = v1.dbRemark;
                                }
                            })
                            var dbShowName = v.dbName;
                            if(v.dbName!= dbRemark&&dbRemark!=''){
                                dbShowName += '-('+ dbRemark+')';
                            }

                            arr.push({id:pId,name: dbShowName,t:v.url,pId:1,open:true,t: v.id});
                            $.each(v.schemaList,function(j,e){
                                var find = 0;
                                var schemaRemark='';
                                var authorization='';
                                $.each($scope.userSchemaList,function(k,s){
                                    if(s.schemaId==e.id){
                                        schemaRemark = s.schemaRemark;
                                        authorization = s.authorization;
                                        find = 1;
                                    }

                                })
                                var schemaShowName = e.schemaName;
                                if(e.schemaName!=schemaRemark&&schemaRemark!=''){
                                    schemaShowName += '-('+schemaRemark+')';
                                }
                                var id = count++;
                                arr.push({id:id,name:schemaShowName ,pId:pId, t:e.id,checked:find==1,open:false});
                                arr.push({id:count++,name:'insert',pId:id,t:"1000",checked:parseAuthorization(authorization,0)});
                                arr.push({id:count++,name:'delete',pId:id,t:"0100",checked:parseAuthorization(authorization,1)});
                                arr.push({id:count++,name:'update',pId:id,t:"0010",checked:parseAuthorization(authorization,2)});
                                arr.push({id:count++,name:'select',pId:id,t:"0001",checked:parseAuthorization(authorization,3)});
                            });
                        });

                        $scope.zNodes = arr;
                    });
                } else {
                    alert(responseObj.errorMsg);
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
        clearInterval(_c);
    },100);
}

//1010 2-->检查1010的第三位是否是1
function parseAuthorization(auth,idx){
    if(!auth){
        return false;
    }
    return auth.charAt(idx)==1;
}
//加载用户的信息,包括SchemaList和DbRemark
function readUserSchemaList($scope){
    var params = new Object();
    params.userId = $scope.currUserId;
    $.ajax({
        url: '/user/doReadSchemaByUserId',
        data :params,
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                $scope.$apply(function () {
                    $scope.userSchemaList = responseObj.dataList;
                    $scope.dbRemarkList = responseObj.dbRemarkList;
                    console.log($scope.userSchemaList);
                });
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}
function userQuery($scope, pageNo) {
    if (!pageNo || pageNo == 0) {
        pageNo = 1;
    }

    var paramObj = new Object();
    paramObj.pageNo = pageNo;

    $.ajax({
        url: '/user/doReadUserList',
        data: paramObj,
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                $scope.$apply(function () {
                    $scope.dataList = responseObj.dataList;
                });
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function userUpdate($scope){
    var paramObj = new Object();

    paramObj.user = $scope.user_update;

    $.ajax({
        url: '/user/doUpdateUser',
        data: paramObj.user,
        type:'post',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                alert('更新成功');
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function userDelete($scope,userIdArr){
    var paramObj = new Object();
    paramObj.userIdStr = userIdArr.join(',');
    $.ajax({
        url: '/user/doDeleteUser',
        data: paramObj,
        type:'post',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                var arr = new Array();
                for(var i=0;i<userIdArr.length;i++){
                    for(var j=0;j<$scope.dataList.length;j++){
                        if($scope.dataList[j].id==userIdArr[i]){
                            arr.push(j);
                        }
                    }
                }
                alert('删除成功');
                $scope.$apply(function () {
                    for(var j=0;j<arr.length;j++){

                        for(var i=0,n=0;i<$scope.dataList.length;i++)
                        {
                            if($scope.dataList[i]!=$scope.dataList[arr[j]])
                            {
                                $scope.dataList[n++]=$scope.dataList[i]
                            }
                        }
                        $scope.dataList.length-=1
                    }
                });
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

//权限更新
function authorizationUpdate($scope){
    var paramObj = new Object();

    paramObj.userId = $scope.currUserId;
    paramObj.schemaIdStr = schemaIdList;
    if(schemaIdList==undefined||schemaIdList==null){
        alert('没有更新');
        return;
    }
    console.log(paramObj);
    $.ajax({
        url: '/user/doUpdateUserSchemaList',
        data: paramObj,
        type:'post',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                alert('更新成功');
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

//数据库实例更新操作
function userInsert($scope){
    var user = $scope.user_insert;
    $.ajax({
        url: '/user/doInsertUser',
        data: user,
        type:'post',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                $scope.dataList.push(responseObj.user);
                alert('插入成功');
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function User_ModalCtrl($scope, $modalInstance) {

    //更新操作
    $scope.update = function () {
        if(confirm('确认更新操作吗?')){
            authorizationUpdate($scope);
            $modalInstance.close();
        }
    };

    $scope.update_user = function(){
        userUpdate($scope);
        $modalInstance.close();
    }
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };

    $scope.save = function(){
        var user = $scope.user_insert;
        if(user.passWord!=user._passWord){
            alert('两次密码输入不一致,请重新输入');
            return;
        }
        userInsert($scope);
        $modalInstance.close();
    }

    $scope.remarkCurrNode = function(){
        if(!currNode){
            alert('请点击任意节点进行备注');
            return;
        }
        var remark = window.prompt('请输入备注名称');
        if($.trim(remark)==''){
            return;
        }
        for(var i=0;i<$scope.zNodes.length;i++){
            if($scope.zNodes[i].id==currNode.id){
//                $scope.$apply = function(){
                    var name = $scope.zNodes[i].name;
                    if(name.indexOf('-(')!=-1){
                        $scope.zNodes[i].name = name.substring(0,name.indexOf('-('))+remark+')';
                    }else{
                        $scope.zNodes[i].name+='-('+remark+')';
                    }
//                }
            }
        }
        if(currNode.pId==1){//上级节点是root,本级节点就是数据库了
            updateDbRemark($scope,currNode.t,remark);
        }else{//Schema节点
            updateSchemaRemark($scope,currNode.t,remark);
        }
    }
};

//更新Schema的备注名称
function updateSchemaRemark($scope,id,remark){
    var paramObj = new Object();
    paramObj.schemaId = id;
    paramObj.schemaRemark = remark;
    paramObj.userId = $scope.currUserId;
    $.ajax({
        url: '/db/doUpdateSchemaRemarkBySchemaIdAndUserId',
        data: paramObj,
        type:'post',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                alert('更新成功');
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

//更新DB的remark
function updateDbRemark($scope,id,remark){
    var paramObj = new Object();
    paramObj.dbId = id;
    paramObj.dbRemark = remark;
    paramObj.userId = $scope.currUserId;
    $.ajax({
        url: '/db/doUpdateDbRemark',
        data: paramObj,
        type:'post',
        success: function (data) {
            var responseObj = $.parseJSON(data);
            if (responseObj.success) {
                alert('更新成功');
            } else {
                alert(responseObj.errorMsg);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}
angular
    .module('inspinia')
    .controller('userCtrl', userCtrl)